package org.grottarossa.tms.aeroflow.ui.core.viewmanager;

import java.util.HashMap;

import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.CloseListener;

/**
 * Implementazione di IViewManager che visualizza le view in finestre popup modali, anche annidate.
 *
 * @author 
 */
public class ModalPopupViewManager extends ViewManagerBase implements IViewManager
{
	private final ComponentContainer m_parentContainer;
	private final HashMap<Component, Window> m_componentWindowMap = new HashMap<Component, Window>();

	/**
	 * @param parentContainer un qualunque componente associato all'application Vaadin corrente
	 * @param rootView la view da considerare corrente nel momento iniziale, pu� essere null
	 */
	public ModalPopupViewManager(ComponentContainer parentContainer, Component rootView)
	{
		m_parentContainer = parentContainer;
		entering(rootView, null);
	}

	@Override
	public Window enterView(final Component view)
	{
		final Window mainWindow = m_parentContainer.getApplication().getMainWindow();

		Window popup = new Window();
		popup.setModal(true);
		popup.setWidth("640px");
		popup.setHeight("480px");
		popup.getLayout().setWidth(100, Sizeable.UNITS_PERCENTAGE);
		popup.getLayout().setHeight(100, Sizeable.UNITS_PERCENTAGE);
		view.setWidth(100, Sizeable.UNITS_PERCENTAGE);
		view.setHeight(100, Sizeable.UNITS_PERCENTAGE);

		mainWindow.addWindow(popup);
		popup.getContent().addComponent(view);

		popup.addListener(new CloseListener() {
			public void windowClose(CloseEvent e) {
				exiting(view);
			}
		});

		entering(view, popup);

		return popup;
	}

	@Override
	public void exitView(Component view)
	{
		if(!m_componentWindowMap.containsKey(view))
			return;

		Window popup = m_componentWindowMap.get(view);
		popup.getParent().removeWindow(popup);
		//exiting(view);
	}

	private void entering(final Component view, Window popup)
	{
		m_componentWindowMap.put(view, popup);
		m_views.push(view);
		fireEnteringEvent(view);
		fireShowingEvent(view);
	}

	private void exiting(Component view)
	{
		fireExitingEvent(view);
		m_views.pop();
		m_componentWindowMap.remove(view);
		fireShowingEvent(m_views.peek());
	}
}
